package com.zjw.hyphenateui.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.havi.bean.MessageBean;
import com.example.havi.ui.ChatActivity;
import com.example.havi.util.LogUtil;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.DateUtils;
import com.zjw.hyphenateui.R;
import com.zjw.hyphenateui.adapter.ConversationAdapter;
import com.zjw.hyphenateui.util.GsonUtils;
import com.zjw.hyphenateui.widget.easyadapter.BaseViewHolder;
import com.zjw.hyphenateui.widget.easyadapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MessageFragment extends BaseFragment {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    private ConversationAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    public void refresh() {
        //获取刷新会话列表
        List<EMConversation> emConversations = loadConversationList();
        mAdapter.clear();
        mAdapter.addAll(emConversations);
    }

    //获取会话列表
    protected List<EMConversation> loadConversationList(){
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }
     //sort conversations according time stamp of last message
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {
                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter = new ConversationAdapter(mContext));
        refresh();
        mAdapter.setOnItemRootClickListener(new ConversationAdapter.OnItemRootClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                EMConversation item = mAdapter.getItem(position);
                EMMessage lastMessage = item.getLastMessage();
                Map<String, Object> map = lastMessage.ext();
                MessageBean messageBean = MessageBean.mapToBean(map);

                if (lastMessage.getChatType() == EMMessage.ChatType.GroupChat) {
                    //群聊
                    ChatActivity.startActivityGroup(MessageFragment.this.getActivityContext(), item.conversationId(), messageBean.getGroupName(), messageBean.getGroupAvatar(), item.conversationId());
                } else {
                    //单聊
                    if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                        //会话中最后一条消息是接收的取avatar和nickName
                        ChatActivity.startActivity(MessageFragment.this.getActivityContext(), item.conversationId(), messageBean.getNickName(), messageBean.getAvatar(), item.conversationId());
                    } else {
                        //会话中最后一条消息是自己发出去的 取toAvatar和toNickName
                        ChatActivity.startActivity(MessageFragment.this.getActivityContext(), item.conversationId(), messageBean.getToNickName(), messageBean.getToAvatar(), item.conversationId());
                    }

                }
            }
        });
    }

}
